package com.system.wechat.service.impl;

import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.wechat.composite.AbstractMenuItem;
import com.system.wechat.composite.MenuComposite;
import com.system.wechat.domain.Menu;
import com.system.wechat.domain.MenuVo;
import com.system.wechat.service.MenuService;
import com.system.wechat.mapper.MenuMapper;
import com.system.wechat.utils.RedisCommonProcessor;
import lombok.SneakyThrows;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author Admin
* @description 针对表【menu(订单明细 订单明细)】的数据库操作Service实现
* @createDate 2024-12-16 16:45:02
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
    implements MenuService{


    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisCommonProcessor redisCommonProcessor;
    /**
     * @return
     */
    @Override
    public MenuComposite fetchAllItems() {
        Object cacheItems = redisCommonProcessor.get("items");
        if(cacheItems != null){
            return (MenuComposite) cacheItems;
        }
        List<Menu> menus = menuMapper.selectList(new QueryWrapper<>());
        MenuComposite composite = generateMenuTree(menus);
        redisCommonProcessor.set("items",composite);
        return composite;
    }

    /**
     * @return
     */
    @Override
    public List<Menu> findMenuOneInfo() {
        return null;
    }

    /**
     * @return
     */
    @Override
    public List<MenuVo> findMenuInfo() {
        //1 创建list集合，用户最终数据封装
        List<MenuVo> finalMenuList = new ArrayList<>();
        //2 查询所有菜单数据（包含一级和二级）
        List<Menu> menuList = baseMapper.selectList(null);
        //3 从所有菜单数据获取所有一级菜单数据（parent_id=0）
        List<Menu> oneMenuList = menuList.stream()
                .filter(menu -> menu.getParentId().longValue() == 0)
                .collect(Collectors.toList());
        //4 封装一级菜单数据，封装到最终数据list集合
        //遍历一级菜单list集合
        for (Menu oneMenu:oneMenuList) {
            //  Menu  --  MenuVo
            MenuVo oneMenuVo = new MenuVo();
            BeanUtils.copyProperties(oneMenu,oneMenuVo);
            //5 封装二级菜单数据（判断一级菜单id和二级菜单parent_id是否相同）
            //如果相同，把二级菜单数据放到一级菜单里面
            List<Menu> twoMenuList = menuList.stream()
                    .filter(menu -> menu.getParentId().longValue() == oneMenu.getId())
                    .collect(Collectors.toList());
            //List<Menu>  --  List<MenuVo>
            List<MenuVo> children = new ArrayList<>();
            for (Menu twoMenu:twoMenuList) {
                MenuVo twoMenuVo = new MenuVo();
                BeanUtils.copyProperties(twoMenu,twoMenuVo);
                children.add(twoMenuVo);
            }
            //把二级菜单数据放到一级菜单里面
            oneMenuVo.setChildren(children);
            //把oneMenuVo放到最终list集合
            finalMenuList.add(oneMenuVo);
        }
        //最终数据返回
        return finalMenuList;
    }

    /**
     * 说明：
     * 自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单。
     * 一级菜单最多4个汉字，二级菜单最多8个汉字，多出来的部分将会以“...”代替。
     * 创建自定义菜单后，菜单的刷新策略是，在用户进入公众号会话页或公众号profile页时，如果发现上一次拉取菜单的请求在5分钟以前，就会拉取一下菜单，如果菜单有更新，就会刷新客户端的菜单。测试时可以尝试取消关注公众账号后再次关注，则可以看到创建后的效果。
     */
    @SneakyThrows
    @Override
    public void syncMenu() {
        List<MenuVo> menuVoList = this.findMenuInfo();
        //菜单
        JSONArray buttonList = new JSONArray();
        for(MenuVo oneMenuVo : menuVoList) {
            JSONObject one = new JSONObject();
            one.put("name", oneMenuVo.getName());
            JSONArray subButton = new JSONArray();
            for(MenuVo twoMenuVo : oneMenuVo.getChildren()) {
                JSONObject view = new JSONObject();
                view.put("type", twoMenuVo.getType());
                if(twoMenuVo.getType().equals("view")) {
                    view.put("name", twoMenuVo.getName());
                    view.put("url", "https://u5u2231821.yicp.fun/#"
                            +twoMenuVo.getUrl());
                } else {
                    view.put("name", twoMenuVo.getName());
                    view.put("key", twoMenuVo.getMeunKey());
                }
                subButton.add(view);
            }
            one.put("sub_button", subButton);
            buttonList.add(one);
        }
        //菜单
        JSONObject button = new JSONObject();
        button.put("button", buttonList);
        this.wxMpService.getMenuService().menuCreate(button.toJSONString());
    }

    private MenuComposite generateMenuTree(List<Menu> menus) {
        List<MenuComposite> menuComposites = new ArrayList<>(menus.size());
        menus.forEach(dbItem -> {
            menuComposites.add(MenuComposite.builder().parentId(dbItem.getParentId())
                    .id(dbItem.getId()).url(dbItem.getUrl()).meunKey(dbItem.getMeunKey())
                    .name(dbItem.getName()).type(dbItem.getType()).createTime(new Date())
                    .updateTime(new Date()).build());

            Map<Long,List<MenuComposite>>  groupList=
                    menuComposites.stream().collect(Collectors.groupingBy(MenuComposite::getParentId));

            menuComposites.stream().forEach(item -> {
                List<MenuComposite> list  = groupList.get(item.getId());
                item.setChild(list == null?new ArrayList<>():list.stream()
                        .map(x -> (AbstractMenuItem)x).collect(Collectors.toList()));
            });
        });
        MenuComposite composite = menuComposites.size() == 0 ? null: menuComposites.get(0);
        return composite;
    }
}




